<!--  -->
<template>
  <div class=''>
    <el-upload ref="upload"
      action="http://tc-guli-file.oss-cn-beijing.aliyuncs.com"
      list-type="picture-card"
      :data="dataObj"
      :multiple="false"
      :before-upload="beforeUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-error="handleError"
      :on-success="handleUploadSuccess"
      :fileList="fileList"
      :before-remove="beforeRemove"
      :class="{hide: value}">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { getUUID } from '@/utils'
export default {
// import引入的组件需要注入到对象中才能使用
  components: {},
  props: {
    value: {
      type: String,
      default: '',
      required: false
    }
  },
  data () {
// 这里存放数据
    return {
      logo: '',
      dialogImageUrl: '',
      dialogVisible: false,
      dataObj: {
        policy: '',
        signature: '',
        ossaccessKeyId: '',
        key: '',
        dir: '',
        host: ''
      },
      // {name,url}
      fileList: []
    }
  },
// 监听属性 类似于data概念
  computed: {},
// 监控data中的数据变化
  watch: {
    value () {
      console.log('我来监听v-model传过来的值 值是:', this.value, this.value === '')
      debugger
      this.logo = this.value
      if (this.logo === '') {
        this.fileList = []
        this.$refs.upload.clearFiles()
      } else {
        this.fileList = []
        this.fileList.push({
          name: this.logo.substring(
                  this.logo.lastIndexOf('/') + 1
                ),
          url: this.logo
        })
      }
    },
    logo (val) {
      this.$emit('input', val)
    }
  },
// 方法集合
  methods: {
    /**
     * 上传成功
     */
    handleUploadSuccess (res, file, fileList) {
      debugger
      console.log('上传成功...')
      this.fileList.pop()
      this.fileList.push({
        name: file.name,
        url: this.dataObj.host + '/' + this.dataObj.key
      })
      this.logo = this.fileList[0].url
    },
    /**
     * 上传前的回调，获取前端上传需要的参数
     */
    beforeUpload (file) {
      console.log(file)
      let _this = this
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl('/third-party/oss/policy'),
          method: 'get',
          params: this.$http.adornParams({})
        })
          .then(({ data }) => {
            console.log('响应的数据', data)
            _this.dataObj.policy = data.data.policy
            _this.dataObj.signature = data.data.signature
            _this.dataObj.ossaccessKeyId = data.data.accessid
            _this.dataObj.key = data.data.dir + getUUID() + '_' + file.name
            _this.dataObj.dir = data.data.dir
            _this.dataObj.host = data.data.host
            console.log(_this.dataObj.policy)
            resolve(true)
          })
          .catch(err => {
            console.log(err)
            this.$message({ type: 'error', message: '上传失败,后端签名获取失败' })
            reject(new Error(err))
          })
      })
    },
    /**
     * 移除一个文件
     */
    handleRemove (file, fileList) {
      debugger
      // TODO 通知调用者
      this.logo = ''
      console.log('handleRemove', file, fileList)
    },
    /**
     * 预览文件
     */
    handlePreview (file) {
      console.log('preview:', file.url)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
      console.log('handlePreview', file)
    },
    /**
     * 超过数量限制的回调
     */
    handleExceed (files, fileList) {
      console.log('handleExceed', files, fileList)
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    /**
     * 移除前的确认回调
     */
    beforeRemove (file, fileList) {
      debugger
      console.log('beforeRemove', file, fileList)
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleError (err, file, fileList) {
      console.log('handleError', err, file, fileList)
    },
    clearAllFiles () {
      this.fileList = []
      this.logo = ''
    }
  },
// 生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
// 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
.hide .el-upload--picture-card {
    display: none;
}
</style>